package com.micro.center.utils;

import com.micro.common.constant.Constant;
import com.micro.center.entity.SysUserEntity;
import com.micro.center.vo.TokenInfoVo;
import com.micro.common.utils.MD5Utils;
import com.micro.common.utils.SnowFlake;
import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Random;

/**
 * @author pan.shun
 * @since 2022/3/15 16:56
 */
public class JwtUtil {


    /**
     * 创建一个Token
     */
    public static String createToken(SysUserEntity sysUserEntity, String tokenId) {
        // 30 分钟失效
        long exp = System.currentTimeMillis() + Constant.TOKEN_CONFIG.EXPIRATION_TIME;
        JwtBuilder builder = Jwts.builder()
                .setId(tokenId)
                .setSubject(sysUserEntity.getUserName())
                .setIssuedAt(new Date())
                .setAudience(randomAudience())
                .signWith(SignatureAlgorithm.HS256, Constant.TOKEN_CONFIG.SIGNINGKEY)
                .setExpiration(new Date(exp));
        return builder.compact();
    }

    /**
     * 随机字符串
     */
    private static String randomAudience() {
        long nextId = new SnowFlake(1, new Random().nextInt(30)).nextId();
        return MD5Utils.stringToMD5(String.valueOf(nextId));
    }

    public static Claims getJwtClaims(String token) {
        return Jwts.parser().setSigningKey(Constant.TOKEN_CONFIG.SIGNINGKEY).parseClaimsJws(token).getBody();
    }

    /**
     * Token 解析
     */
    public static TokenInfoVo getJwtClaimsDetail(String token) {
        Claims claims = Jwts.parser().setSigningKey(Constant.TOKEN_CONFIG.SIGNINGKEY).parseClaimsJws(token).getBody();
        return TokenInfoVo.builder().userId(claims.getId()).audience(claims.getAudience()).userName(claims.getSubject()).build();
    }


    public static TokenInfoVo getJwtClaimsDetailByRequest(HttpServletRequest request) {
        String token = request.getHeader(Constant.TOKEN_CONFIG.TOKEN_KEY);
        if (StringUtils.isEmpty(token) || "null".equals(token)) {
            token = request.getParameter(Constant.TOKEN_CONFIG.TOKEN_KEY);
        }
        if (!StringUtils.isEmpty(token) && !"null".equals(token)) {
            Claims claims = Jwts.parser().setSigningKey(Constant.TOKEN_CONFIG.SIGNINGKEY).parseClaimsJws(token).getBody();
            return TokenInfoVo.builder().userId(claims.getId()).audience(claims.getAudience()).userName(claims.getSubject()).build();
        } else {
            return TokenInfoVo.builder().userId("0").build();
        }
    }


}